#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   app.py
@Time    :   2021/03/16 02:01:26
@Author  :   watalo 
@Version :   1.0
@Contact :   watalo@163.com
'''

# here put the import lib
from peewee import *
from datetime import date
from datetime import timedelta
from docx.shared import Inches
from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt, Length
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT,WD_ALIGN_VERTICAL





# 为了搞清楚背后的动作，官方推荐使用：
# import logging
# logger = logging.getLogger('peewee')
# logger.addHandler(logging.StreamHandler())
# logger.setLevel(logging.DEBUG)

# 前期配置
database = SqliteDatabase('zxcvb23423es2sdf235vdfghjertyu34rt.db')

# 数据结构
class BaseModel(Model):
   class Meta():
       database = database


class Member(BaseModel):
    name = CharField(unique=True)


class Report(BaseModel):
    member = ForeignKeyField(Member, backref='reports', lazy_load=True)
    date = DateField() # 到底要不要加默认值？？
    info = TextField(null=False)


class Project(BaseModel):
    '''
    单个项目的Model：
    属性：
        name：企业名称；member:管户人员；scheme:方案； info:进程记录(列表统计)、状态（由flag操作）、启动日期、启用标签
    方法：
        - forward():状态向前推进一步
        - 

    '''
    name = CharField(unique=True)
    member = ForeignKeyField(Member, backref='projs', lazy_load=True)
    scheme = CharField(default = '')
    info = TextField(default = '')
    flag = IntegerField(default= 0, constraints=[Check('flag<=5') ])
    date = DateField(default =  date(2000,1,1))
    tag = CharField(default = '')


    def status(self):
        status_list = ['1.营销阶段','2.调查阶段',
                       '3.审查阶段','4.审批阶段',
                       '5.已批未投','6.完成投放']
        return status_list[self.flag]


    def forward(self):
        with database.atomic():

            if self.flag <= 5:
                self.flag += 1
                
            else:
                self.flag = 5
            self.save()
        res = self.status()
        print('{}项目当前状态：{}'.format(self.name, res))


    def back(self):
        with database.atomic():   
            if self.flag > 0:
                self.flag -= 1
            else:
                self.flag = 0
            self.save()
        res = self.status()   
        print('{}项目当前状态：{}'.format(self.name, res))


    def change_scheme(self, new_scheme):
        with database.atomic():
            self.scheme = new_scheme
            self.save()
        
        print('{}的新方案是：{}'.format(self.name, self.scheme))


    def drop(self):
        with database.atomic():
            self.tag = '暂停项目'
            self.save()
        print('{}项目已暂停，若需重新启用，请使用restart函数'.format(self.name))


    def restart(self):
        with database.atomic():
            self.tag = ''
            self.save()
        print('{}项目已重新启用，若需放弃本项目，请使用drop函数'.format(self.name))


    def flash_info(self, info):
        with database.atomic():
            list_info = [self.info]
            info = str('{}:{}'.format(date.today(), info))
            list_info.append(info)
            if self.info == '':
                self.info = ''.join(list_info)
            else:
                self.info = ';'.join(list_info)    
            self.save()
        print('{}项目的备注信息：{}'.format(self.name, self.info))

class Product(BaseModel):
    proj     = ForeignKeyField(Project, backref='prods',lazy_load=True)
    Member   = ForeignKeyField(Member, backref='my_prods', lazy_load=True)
    catagory = CharField()
    amount   = FloatField()
    balance  = FloatField()
    bargain  = FloatField(null=False)
    start_date  = DateField()
    end_date    = DateField()


# 调用函数
def db_init():
    if database.is_closed():
        database.connect()
        database.create_tables([Member, Report, Project, Product])
    else:
        database.create_tables([Member, Report, Project, Product])

    database.close()


def new_member(name_):
    with database:
        res = Member.get_or_create(name = name_)
        query = Member.select()
        print('团队成员：')
        for q in query:
            print('     '+q.name)


def new_report(member_name, date_, info_):
    with database:
        if Member.get_or_none(Member.name == member_name) != None:
            member_obj = Member.get(Member.name == member_name)
            Report.create(member = member_obj, date = date_, info = info_)
        else:
            return '{}成员不存在，请仔细检查！'.format(member_name)
        query = Report.select().join(Member).where(Member.name == member_name)
        print(''.join([member_name, '工作记录：']))
        for report in query:
            print('{}：{}'.format(report.date, report.info))


def output_report():

    #报告字体设置
    doc = Document()
    doc.styles['Normal'].font.name = 'Times New Roman'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    #标准段落格式
    def standard_para(text, bold=False):
        para = doc.add_paragraph()
        para.paragraph_format.first_line_indent = Pt(24)
        content = para.add_run(text)
        content.bold = bold
        content.font.name = '宋体'
        content.font.size = Pt(12)


    #标题
    title = doc.add_heading('',level=0).add_run('营业部工作周报（{}）'.format(date.today()))
    title.font.name = '黑体'
    title.font.size = Pt(16)
    title_1 = doc.add_heading('',level=1).add_run('一、本周工作周报')
    title_1.font.name = '黑体'
    title_1.font.size = Pt(14)
    #工作周报循环
    members = Member.select()
    i = 1
    for member in members:
        name_para = standard_para('、'.join([str(i), member.name]), True)
        i += 1
        # name_para.blod()
        day = date.today()
        day_7_before = date.today() - timedelta(weeks=1)
        for report in Report.select().where(Report.date.between(day_7_before, day)):
            if report.member.name == member.name:
                text = '{}： {}'.format(report.date, report.info)
                standard_para(text)
            else:
                pass
    
    #标题
    title_2 = doc.add_heading('',level=1).add_run('二、项目进展一览表')
    title_2.font.name = '黑体'
    title_2.font.size = Pt(14)
    #设置表格
    table = doc.add_table(rows = 1, cols = 5, style='Dark List Accent 1')
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    hdr_cells = table.rows[0].cells
    for cell in hdr_cells:
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    hdr_cells[0].text = '客户名称'
    hdr_cells[1].text = '客户经理'
    hdr_cells[2].text = '融资方案'
    hdr_cells[3].text = '项目状态'
    hdr_cells[4].text = '项目进展'
    query = Project.select().where(Project.tag == '').order_by(Project.flag)
    for q in query:
        row_cells = table.add_row().cells
        for cell in row_cells:
            cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
        row_cells[0].text = q.name
        row_cells[1].text = q.member.name
        row_cells[2].text = q.scheme
        row_cells[3].text = q.status()
        row_cells[4].text = q.info

    # 投放项目
    title_3 = doc.add_heading('', level = 1).add_run('三、投放计划')
    title_3.font.name = '黑体'
    title_3.font.size = Pt(14)
    table_3 = doc.add_table(rows = 2, cols = 5, style='Dark List Accent 1')
    table_3.alignment = WD_TABLE_ALIGNMENT.CENTER
    hdr_cells_3 = table_3.rows[0].cells
    for cell in hdr_cells:
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    hdr_cells_3[0].text = '客户名称'
    hdr_cells_3[1].text = '客户经理'
    hdr_cells_3[2].text = '产品方案'
    hdr_cells_3[3].text = '投放时间'
    hdr_cells_3[4].text = '项目进展'

    # 网点提升项目
    title_4 = doc.add_heading('', level = 1).add_run('四、网点提升项目')
    title_4.font.name = '黑体'
    title_4.font.size = Pt(14)
    table_4 = doc.add_table(rows = 2, cols = 5, style='Dark List Accent 1')
    table_4.alignment = WD_TABLE_ALIGNMENT.CENTER
    hdr_cells_4 = table_4.rows[0].cells
    for cell in hdr_cells_4:
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    hdr_cells_4[0].text = '客户名称'
    hdr_cells_4[1].text = '客户经理'
    hdr_cells_4[2].text = '方案类型'
    hdr_cells_4[3].text = '完成时间'
    hdr_cells_4[4].text = '项目进展'

            
    doc.save('营业部工作周报（{}）.docx'.format(date.today()))
    

def new_project(name_, member_):
    with database.atomic():
        proj = Project.create(name = name_, 
                              member = Member.select().where(Member.name == member_), )
    r = proj.status()
    res = ('新项目:{n}授信项目已记录，由{m}管理，目前状态为{s}'
           .format(n = name_, m = proj.member.name, s = r))
    print(res)
    return proj



def new_product(name_, catagory_, amount_, balance_, bargain_, start_date_, end_date_):
    prod = Product.create(
        proj = Project.select().where(Project.name == name_), 
        member = Member.select().join(Project).where(Project.name == name_),
        catagory = catagory_, 
        amount = amount_, 
        balance = balance_, 
        bargain = bargain_, 
        start_date = start_date_, 
        end_date = end_date_,
    )
    res = '新增投放：{}{}{}'.format(name_, catagory_, amount_)
    print(res)
    return res
    

def change_memb(name_changed, new_name):
    memb_obj = Member.get(Member.name == name_changed)
    memb_obj.name = new_name
    memb_obj.save()
    print('{}已更正为{}'.format(name_changed, new_name))


def delete_memb(name_):
    '''
    删除成员，会引发Project和Product的错误
    所以删除成员 = 将成员替换成'待定'可能更好
    '''
    try:
        new_member('待定')
        change_memb(name_, '待定')
        return '团队成员已删除，管户成员待定'
    except:
        return '【错误】：1.成员已删除；2.已设置为“待定”'



def output_project():

    #报告字体设置
    doc = Document()
    doc.styles['Normal'].font.name = 'Times New Roman'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    #标准段落格式
    def standard_para(text, bold=False):
        para = doc.add_paragraph()
        para.paragraph_format.first_line_indent = Pt(24)
        content = para.add_run(text)
        content.bold = bold
        content.font.name = '宋体'
        content.font.size = Pt(12)

    #标题
    title_1 = doc.add_heading('',level=1).add_run('二、项目进展一览表')
    title_1.font.name = '宋体'
    title_1.font.size = Pt(14)
    #设置表格
    table = doc.add_table(rows = 1, cols = 5 )
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '客户名称'
    hdr_cells[1].text = '客户经理'
    hdr_cells[2].text = '融资方案'
    hdr_cells[3].text = '项目状态'
    hdr_cells[4].text = '项目进展'
    query = Project.select().where(Project.tag == '').order_by(Project.flag)
    for q in query:
        row_cells = table.add_row().cells
        row_cells[0].text = q.name
        row_cells[1].text = q.member.name
        row_cells[2].text = q.scheme
        row_cells[3].text = q.status()
        row_cells[4].text = q.info

            
    doc.save('营业部项目进展（{}）.docx'.format(date.today()))
    




# if __name__ == '__main__':
#     output_report() 